﻿using System.Data.Entity;

namespace TaskManager.DataAccess.Repositories
{
    /// <summary>
    /// Drops and creates the database if model changes
    /// </summary>
    /// <remarks>Provides the same functionality as <see cref="DropCreateDatabaseIfModelChanges"/>. Adds SQL constraints when database is constructed.</remarks>
    internal class DatabaseInitializer : IDatabaseInitializer<TaskManagerDbContext>
    {
        public void InitializeDatabase(TaskManagerDbContext context)
        {
            if (context.Database.Exists() && !context.Database.CompatibleWithModel(false))
                context.Database.Delete();

            if (!context.Database.Exists())
            {
                context.Database.Create();

                // Manually add constraints
                context.Database.ExecuteSqlCommand("ALTER TABLE Projects ADD CONSTRAINT UniqueProjectName UNIQUE (Name)");
                context.Database.ExecuteSqlCommand("ALTER TABLE Users ADD CONSTRAINT UniqueUserName UNIQUE (Name)");
            }
        }
    }
}